package com.studycloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.studyclud.constant.ConstantInt.INTEGERVUALE_MAX;

/**
 * @author JP
 * 自定义轮询的实现类
 */
@Component
public class MyLB implements LoadBalancer
{
    /**
     * 保证原子性
     */
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement()
    {
        int current;
        int next;
        do
        {
            current = this.atomicInteger.get();
            next = current >= INTEGERVUALE_MAX ? 0 : current + 1;

        }while (!this.atomicInteger.compareAndSet(current,next));

        return  next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList)
    {
        int size = getAndIncrement() % serviceInstanceList.size();

        return null;
    }
}
